package com.example.spzx.Service.impl;

import com.alibaba.excel.EasyExcel;
import com.example.exception.OmegaException;
import com.example.spzx.ExcelListener;
import com.example.spzx.Mapper.CategoryMapper;
import com.example.spzx.Service.CategoryService;
import com.example.spzx.model.entity.product.Category;
import com.example.spzx.model.vo.common.ResultCodeEnum;
import com.example.spzx.model.vo.product.CategoryExcelVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    public List<Category> getlist(){
        List<Category> list=categoryMapper.getall();

        return getchildren(list,0L);
    }
    public List<Category> getchildren(List<Category> list,Long pid){
        List<Category> children=new ArrayList<>();
        for (Category category:list){
            if(category.getParentId().equals(pid)){
                category.setChildren(getchildren(list,category.getId()));
                children.add(category);
            }
        }
        return children;
    }
    public  void exportData(HttpServletResponse httpServletResponse){
        try {
            httpServletResponse.setContentType("application/vnd.ms-excel");
            httpServletResponse.setCharacterEncoding("utf-8");
            String fileName= URLEncoder.encode("分类数据","UTF-8");
            httpServletResponse.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            List<Category> categoryList=categoryMapper.getall();
            List<CategoryExcelVo> categoryExcelVos=new ArrayList<>(categoryList.size());
            for (Category category:categoryList){
                CategoryExcelVo categoryExcelVo=new CategoryExcelVo();
                BeanUtils.copyProperties(category,categoryExcelVo,CategoryExcelVo.class);
                categoryExcelVos.add(categoryExcelVo);
            }
            EasyExcel.write(httpServletResponse.getOutputStream(),CategoryExcelVo.class).sheet("分类数据").doWrite(categoryExcelVos);


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public  void importData(MultipartFile file){
        try{
            ExcelListener<CategoryExcelVo> excelVoExcelListener=new ExcelListener<>(categoryMapper);
            EasyExcel.read(file.getInputStream(),CategoryExcelVo.class,excelVoExcelListener).sheet().doRead();
        }catch (IOException e){
            throw new OmegaException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
